var devUrl = 'http://www.xmdabao.com:8080'; // 地址前缀
// var devUrl = 'http://192.168.0.116:4000'; // 地址前缀
var provUrl = 'http://47.96.66.69:4000'; // 地址前缀

var baseUrl = devUrl; // 测试环境
// var baseUrl = provUrl; // 生产环境

var myHost = window.location.protocol + "//" + window.location.host;

var appTimeout, appvId, TOKEN = "VID";

//判断是否是数字
function isNumber(value) {
    var patrn = /^(([1-9]\d{0,5})|0)(\.\d{1,2})?$/;
    if (patrn.exec(value) == null || value == "") {
        return false
    } else {
        return true
    }
}

//截取图片mini_
//function substrImg(src) {
//    var miniIdx = src.lastIndexOf('.');
//    var miniP = src.substr(0, miniIdx - 5) + src.substr(miniIdx);
//    return miniP;
//}
/*地址栏获取参数*/
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

var interval = 1000;//指定时间为：1秒
function countDown(_date) {
    var $day = $('.day'), $hour = $('.hour'), $min = $('.min'), $sec = $('.sec'), $countDown = $('.push_msg_countDown');

    var sForDay = 60 * 60 * 24;
    var now = new Date();            //调用系统时间,当前时间
    var endDate = _date;   //结束时间
    var leftTime = endDate.getTime() - now.getTime();//剩下的时间
    var leftsecond = parseInt(leftTime / 1000);//剩下的秒数
    var day_1 = Math.floor(leftsecond / sForDay);//剩余天数
    var hour = Math.floor((leftsecond - day_1 * sForDay) / 3600);//剩余小时
    var minute = Math.floor((leftsecond - day_1 * sForDay - hour * 60 * 60) / 60);//剩余分钟
    var second = Math.floor(leftsecond - day_1 * sForDay - hour * 3600 - minute * 60);//剩余秒数
    $day.text(day_1);
    $hour.text(hour);
    $min.text(minute);
    $sec.text(second);
    if (now >= endDate) {
        clearTimeout(appTimeout);
        $countDown.css("color", "red").html("活动结束了");
        return;
    }
}

// ajax公共函数
function appAjax(obj) {
    var url = obj.url;
    var myData = obj.data;
    if (!myData) myData = {};
    addLoading(obj.chilren);
    var conType = '';
    if (obj.method === 'post') {
        conType = 'application/json;charset=UTF-8';
        myData = JSON.stringify(myData)
    } else {
        conType = 'application/x-www-form-urlencoded;charset=UTF-8';
    }
    $.ajax({
        type: obj.method,
        url: baseUrl + url,
        contentType: conType,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        data: myData,
        dataType: "json",
        success: function (r) {
            removeLoading();
            if (r.code === '0') {
                obj.success(r.data)
            } else {
               /* // errorModal(r.msg)
                // if (obj.error) {
                //     obj.error(r)
                // }*/
            }
        }
       /* error: function (error) {
            removeLoading();
            errorModal('System error');
            console.log(error)
            // if (error.responseJSON) {
            //     errorModal(error.responseJSON.msg);
            // } else {
            //     errorModal('系统错误');
            // }
        }*/
    });
}

// 添加loading层
function addLoading(children) {
    var el = $("body");
    // if (children) {
    //     el = $(window.parent.document).find("body");
    // }
    // var loadingSrc=  (baseUrl === provUrl) ? '/yykShop/assets/images/loading.gif' : '/swimming_mall/src/assets/images/loading.gif';
    el.append('<div class="loadingCeng text_center"><img src="./static/images/loading.gif" alt="loading"/></div>');
}

// 移除loading层
function removeLoading() {
    setTimeout(function () {
        $(".loadingCeng").remove();
        // $("body").find(".loadingCeng").remove();
    }, 200);
}

// 定义改变密码显示类型
function changePwdType() {
    var seePwd = $('.icon_eye'), password = $('.pwd');
    seePwd.toggleClass('seePwd');
    password.attr('type', (password.attr('type') == 'text') ? 'password' : 'text');
}

//发送倒计时
function sendCode(dom) {
    if (dom.hasClass('verificationCode')) {
        dom.addClass('disabled');
        var countdown = 60;

        function settime(val) {
            if (countdown == 0) {
                dom.removeClass('disabled').attr('disabled', false).val('获取验证码');
                countdown = 60;
            } else {
                dom.val('重新发送(' + countdown + ')').attr('disabled', 'true');
                countdown--;
                //创建定时器
                var timer = setTimeout(function () {
                    settime(val)
                }, 1000)
            }
        }

        settime();
    }
}

//suamit不可以点击
function unSubmit(bom) {
    bom.attr("disabled", false);
}

//正则截取字段
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

var freshTime = 6; // 城市信息存1一个小时---单位小时
// 存储cookie
function setCookie(name, value) {
    var exp = new Date();
    exp.setTime(exp.getTime() + freshTime * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

// 读取cookie
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

//删除cookie
function delCookie(name){//为了删除指定名称的cookie，可以将其过期时间设定为一个过去的时间
    var date = new Date();
    date.setTime(date.getTime() - 10000);
    document.cookie = name + "=a; expires=" + date.toGMTString();
}

function arrayContain(arr, val) {
    $(arr).each(function (item) {
        if (item == val) {
            return true;
        }
    });
    return false;
}

function errorModal(word) { // 错误弹窗
    $("body").append('<div class="alert alert-error"><a class="alert-close" onclick="removeAlert()">×</a><strong>Error!</strong>' + word + '</div>')
    setTimeout(function () {
        removeAlert()
    }, 2000)
}

function successModal(word) { // 成功弹窗
    $("body").append('<div class="alert alert-success"><a class="alert-close" onclick="removeAlert()">×</a><strong>Success!</strong>' + word + '</div>')
    setTimeout(function () {
        removeAlert()
    }, 2000)
}

function removeAlert () { // 关闭错误弹窗
    setTimeout(function () {
        $(".alert").remove();
    }, 100);
}

function removeMyAccount () { // 我的账户弹窗
    $(".my-account-content").remove();
}

// 退出登录
function userExit() {
    appAjax({
        url: '/app/mall/user/logout',
        method: 'get',
    })
    delCookie('name');
    delCookie('avatar');
    window.location.href = 'index.html';
}

function goToAccount() { // 跳转我的账户
    if (!getCookie('name')) {
        window.parent.document.location.href = './login.html';
    } else {
        window.parent.document.location.href = './accountInformation.html';
    }
}


function resetContentHeight() { // content最小高度
    $("body #content").css({
        'min-height': $(window).height() - 620 + 'px'
    })
}

// 文件上传
function uploadFile(file, operate) {
    var formFile = new FormData();
    formFile.append("action", "UploadVMKImagePath");
    formFile.append("file", file); //加入文件对象   file为传递给后台的参数，可以模仿form中input的name值。

    var data = formFile;
    addLoading();
    $.ajax({
        url: baseUrl + "/oss/upload",
        data: data,
        type: "post",
        dataType: "json",
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false, //必须
        success: function (result) {
            // console.log(result)
            removeLoading();
            operate(result);
        },
        error: function (error) {
            removeLoading();
            errorModal('System error');
            console.log(error)
        }
    })
}

// 字典查询
function queryDistInfo(val, operate) {
    appAjax({
        url: '/app/dict/' + val,
        method: 'get',
        success: function (res) {
            operate(res);
        }
    })
}

// 验证手机号
function validateMobile(phone) {
    let result = true;
    var isMob = /^((\+?86)|(\(\+86\)))?(13[0123456789][0-9]{8}|15[012356789][0-9]{8}|18[012356789][0-9]{8}|14[57][0-9]{8}|17[3678][0-9]{8})$/;
    if (!isMob.test(phone)) {
        result = false;
    }
    return result;
}

// 验证为空
function validatenull(val) {
    if (val instanceof Array) {
        if (val.length == 0) return true;
    } else if (val instanceof Object) {
        if (JSON.stringify(val) === '{}') return true;
    } else {
        if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
        return false;
    }
    return false;
};

;(function ($) {
    $(function () {
        // 导航hover事件
        $(".header-nav .aboutUs").hover(function () {
            $("#aboutUs").show();
            $("#dynamicInfo").hide();
        })
        $(".header").hover(function () {}, function () {
            $("#aboutUs").hide();
            $("#dynamicInfo").hide();
        })
        $(".header-nav .dynamicInfo").hover(function () {
            $("#dynamicInfo").show();
            $("#aboutUs").hide();
        })
        // console.log(111)
        // document.oncontextmenu=new Function("event.returnValue=false");
        // document.onselectstart=new Function("event.returnValue=false");
    })
})(jQuery);
